package com.celebriosoftware.client;

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.lang3.StringEscapeUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.HttpAuthHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.celebriosoftware.celebrioclient.R;

@SuppressLint("SetJavaScriptEnabled")
public class BrowserActivity extends Activity {

	private BrowserWebView browser;
	private EditText urlTextBox;
	private Button goButton;
	private TextView internetLabel;
	private TextView desktopLabel;
	private ImageButton reload;
	private ImageButton goBack;
	private ImageButton upButton;
	private ImageButton downButton;
	private LinearLayout rightfooter;
	private ProgressBar pBar;
	private HttpAuthHandler loginHandler;
	private RelativeLayout loginScreen;
	private EditText userName;
	private EditText password;
	private Button submit;
	private Button cancel;
	private FrameLayout topLayout;
	private SharedPreferences pref;
	
	//Used for hiding bottom tablet controls panel
	private RelativeLayout mainLayout;
	private final Handler rHandler = new Handler();
	private Repeater repeater;

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.actvity_browser);
		internetLabel = (TextView) findViewById(R.id.internetLabel);
		loginScreen = (RelativeLayout) findViewById(R.id.loginScreen);
		browser = (BrowserWebView) findViewById(R.id.web_browser);
		urlTextBox = (EditText) findViewById(R.id.urlTextbox);
		goButton = (Button) findViewById(R.id.goButton);
		topLayout = (FrameLayout) findViewById(R.id.leftLayout);
		goBack = (ImageButton) findViewById(R.id.backButton);
		//home = (ImageButton) findViewById(R.id.homeButton);
		reload = (ImageButton) findViewById(R.id.reloadButton);
		rightfooter = (LinearLayout) findViewById(R.id.bottomRightBar);
		upButton = (ImageButton) findViewById(R.id.upButton);
		downButton = (ImageButton) findViewById(R.id.downButton);
		pBar = (ProgressBar) findViewById(R.id.pB1);
		
		desktopLabel = (TextView) findViewById(R.id.leftFooterText);

		Typeface type = Typeface.createFromAsset(getAssets(),
				"fonts/XXII-SinozDSP_Medium.otf");
		internetLabel.setTypeface(type);
		desktopLabel.setTypeface(type);
		browser.getSettings().setJavaScriptEnabled(true);
		browser.getSettings().setSupportZoom(true);

		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
			browser.getSettings().setBuiltInZoomControls(true);
			browser.getSettings().setDisplayZoomControls(false);
		}
		
		//Hiding bottom tablet control panel
		mainLayout =((RelativeLayout) findViewById(R.id.BrowserLayout));
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
			repeater=new Repeater();
			rHandler.postDelayed(repeater, 100);
		}

		browser.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				return false;
			}

			@Override
			public void onReceivedHttpAuthRequest(WebView view,
					HttpAuthHandler handler, String host, String realm) {
				loginScreen.setVisibility(View.VISIBLE);
				userName = (EditText) findViewById(R.id.userName);
				password = (EditText) findViewById(R.id.password);

				submit = (Button) findViewById(R.id.submitButton);
				cancel = (Button) findViewById(R.id.cancelButton);
				loginHandler = handler;

				submit.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {

						loginHandler.proceed(userName.getText().toString()
								.trim(), password.getText().toString().trim());
						loginScreen.setVisibility(View.INVISIBLE);

					}
				});

				cancel.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {

						loginHandler.cancel();
						loginScreen.setVisibility(View.INVISIBLE);

					}

				});

			}
			
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
						RelativeLayout.LayoutParams.WRAP_CONTENT,
						RelativeLayout.LayoutParams.WRAP_CONTENT);
				params.setMargins(0, findViewById(R.id.middleBar).getBottom()+4, 0, 0);
				view.setLayoutParams(params);
				urlTextBox.setText(url);			
			}
			
			@Override
			public void onPageFinished(WebView view, String url) {
				RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
						RelativeLayout.LayoutParams.WRAP_CONTENT,
						RelativeLayout.LayoutParams.WRAP_CONTENT);
				params.setMargins(0, findViewById(R.id.middleBar).getBottom()+4, 0, 0);
				view.setLayoutParams(params);
				urlTextBox.setText(url);
				super.onPageFinished(view, url);
			}
		});

		urlTextBox.setOnEditorActionListener(new OnEditorActionListener() {
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_NEXT
						|| actionId == EditorInfo.IME_ACTION_DONE) {
					goButton.performClick();
					InputMethodManager inputManager = (InputMethodManager) getApplicationContext()
							.getSystemService(Context.INPUT_METHOD_SERVICE);
					inputManager.hideSoftInputFromWindow(getCurrentFocus()
							.getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);

				}
				return true;

			}
		});

		browser.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int progress) {
				if (progress < 100 && pBar.getVisibility() == ProgressBar.GONE) {
					pBar.setVisibility(ProgressBar.VISIBLE);

				}
				pBar.setProgress(progress);
				if (progress == 100) {
					pBar.setVisibility(ProgressBar.GONE);

				}
			}

		});
			
		String uri=this.getIntent().getStringExtra("com.celebriosoftware.client.uri");
		if(uri!=null) {
			browser.loadUrl(uri);
		}
		else {
	        SharedPreferences savedURL = this.getPreferences(MODE_PRIVATE);
		    browser.loadUrl(savedURL.getString("savedUrl", MainActivity.BROWSER_DEFAULT_URL));			
		}
		
		goButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				browser.loadUrl(parseUrl(urlTextBox.getText().toString()));

			}
		});
		
		goBack.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if(browser.canGoBack())
					browser.goBack();
				else browser.loadUrl(MainActivity.BROWSER_DEFAULT_URL);
			}
		});
		
		/*home.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				browser.loadUrl(MainActivity.BROWSER_DEFAULT_URL);
			}
		});*/
		
		reload.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				browser.reload();

			}
		});

		upButton.setOnTouchListener(new OnTouchListener() {

			private Handler mHandler;

			public boolean onTouch(View v, MotionEvent event) {

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if (mHandler != null)
						return true;
					mHandler = new Handler();

					mHandler.post(mAction);
					break;
				case MotionEvent.ACTION_UP:
					if (mHandler == null)
						return true;
					mHandler.removeCallbacks(mAction);
					mHandler = null;
					break;

				}
				return false;

			}

			Runnable mAction = new Runnable() {
				public void run() {
					//if (browser.getScrollY() - 35 < 0) {
					//	browser.animateBrowser(-35);
					//} else {
						browser.arrowScrollUp(-20);
					//}

					mHandler.postDelayed(this, 50);
				}
			};
		});

		downButton.setOnTouchListener(new OnTouchListener() {

			private Handler mHandler;

			public boolean onTouch(View v, MotionEvent event) {

				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					if (mHandler != null)
						return true;
					mHandler = new Handler();

					mHandler.post(mAction);
					break;
				case MotionEvent.ACTION_UP:
					if (mHandler == null)
						return true;
					mHandler.removeCallbacks(mAction);
					mHandler = null;
					break;

				}
				return false;

			}

			Runnable mAction = new Runnable() {
				public void run() {

					browser.arrowScrollDown(20);

					mHandler.postDelayed(this, 50);
				}
			};

		});

		rightfooter.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				//should be reworked to go to background instead of finishing
				//browserActivity.moveTaskToBack(true);				
				finish();

			}
		});

	}

	@Override
	protected void onStop() {
		super.onStop();
		pref = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor ed = pref.edit();
        ed.clear();
        ed.putString("savedUrl", browser.getUrl());
        ed.commit();
	}

	public void onWindowFocusChanged(boolean hasFocus) {

		super.onWindowFocusChanged(hasFocus);
		int width = browser.getWidth();

		if (width / 2 < topLayout.getWidth()) {
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,
					LinearLayout.LayoutParams.MATCH_PARENT, 50);
			topLayout.setLayoutParams(params);
		}

	}

	private String parseUrl(String url) {
		String escapedUrl = StringEscapeUtils.escapeJava(url);
		String parsedUrl;
		String prefix = "www";

		Boolean hasWebPrefix = escapedUrl.startsWith(prefix);

		if (hasWebPrefix || !escapedUrl.contains("://"))
			escapedUrl = "http://" + escapedUrl;

		parsedUrl = escapedUrl;
		try {
			URL wellFormedUrl = new URL(escapedUrl);
			parsedUrl = wellFormedUrl.toExternalForm();
		} catch (MalformedURLException e) {
			Log.i("Celebrio-ParseUrl", e.toString());
		}

		return parsedUrl;
	}
	
	//Periodically fades native UI
	@SuppressLint("NewApi")
	private class Repeater implements Runnable {
		public void run() {
			mainLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
			rHandler.removeCallbacks(repeater);
			rHandler.postDelayed(this, 2000);
		}
	};
}
